package com.example.springboot.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Book;
import com.example.springboot.service.BookService;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;


@CrossOrigin
@RestController
@RequestMapping("/book")
public class BookController{
    
    @Autowired
    BookService bookService;
    

    @PostMapping("/add")
    public Result add(@RequestBody Book book){
        try{
            bookService.save(book);
        }catch(Exception e){
            return Result.error("插入数据错误");
        }
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Book book){
        try{
            bookService.updateById(book);
        }catch(Exception e){
            return Result.error("更改数据错误");
        }
        return Result.success();
    }

    @DeleteMapping("/delete/{ISBN}")
    public Result delete(@PathVariable String ISBN){
        try{
            bookService.removeById(ISBN);
        }catch(Exception e){
            return Result.error("删除数据错误");
        }
        return Result.success();
    }

    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<String> isbns) {
        bookService.removeBatchByIds(isbns);
        return Result.success();
    }

    @GetMapping("/selectAll")
    public Result selectAll(){
        List<Book> bookList= bookService.list();
        return Result.success(bookList);
    }

    @GetMapping("/selectByIsbn/{isbn}")
    public Result selectByIsbn(@PathVariable String isbn){
        Book book=bookService.getById(isbn);
        return Result.success(book);
    }

    @GetMapping("/selectByState/{state}")
    public Result selectByState(@PathVariable String state){
        List<Book> bookList3= bookService.selectByState(state);
        return Result.success(bookList3);
    }
    @GetMapping("/selectByShoptime/{shoptime}")
    public Result selectByShoptime(@PathVariable String shoptime){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        // 使用 leftLike 方法来匹配年月开头的部分
        queryWrapper.like("shoptime", shoptime);
        List<Book> list4= bookService.list(queryWrapper);
        return Result.success(list4);
    }
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam String isbn,
                            @RequestParam String name,
                            @RequestParam String author,
                            @RequestParam String type) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<Book>();
        queryWrapper.like(StrUtil.isNotBlank(isbn), "isbn", isbn);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(author), "author", author);
        queryWrapper.like(StrUtil.isNotBlank(type), "type", type);
        queryWrapper.eq( "state", "在售");
        Page<Book> page = bookService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }
    @GetMapping("/selectByPage1")
    public Result selectByPage1(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam String isbn,
                            @RequestParam String shoptime) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<Book>();
        queryWrapper.like(StrUtil.isNotBlank(isbn), "isbn", isbn);
        queryWrapper.like(StrUtil.isNotBlank(shoptime), "shoptime", shoptime);
        Page<Book> page = bookService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(page);
    }

        @GetMapping("/export")
        public void exportData(@RequestParam(required = false) String isbn,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) String author,
                           @RequestParam(required = false) String type,
                           @RequestParam(required = false) String isbns,
                           HttpServletResponse response) throws IOException{
        ExcelWriter writer =ExcelUtil.getWriter(true);
        List<Book> list;
        QueryWrapper<Book> queryWrapper = new QueryWrapper<Book>();
        if(StrUtil.isNotBlank(isbns)){
            List<String> isbnsArr=Arrays.stream(isbns.split(",")).collect(Collectors.toList());
            queryWrapper.in("isbn",isbnsArr);
        }else{
            //第一种全部导出或者条件导出
            queryWrapper.like(StrUtil.isNotBlank(isbn), "isbn", isbn);
            queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
            queryWrapper.like(StrUtil.isNotBlank(author), "author", author);
            queryWrapper.like(StrUtil.isNotBlank(type), "type", type);
        }
        list=bookService.list(queryWrapper);
        writer.write(list,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("书籍信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Book> bookList = reader.readAll(Book.class);
        // 写入数据到数据库
        try {
            bookService.saveBatch(bookList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("数据批量导入错误");
        }
        return Result.success();
    }
}